package com.vancouver.knows.business.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.graphics.Bitmap;

import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.pangu.bean.PageableResult;
import com.pangu.service.ActionException;
import com.pangu.service.IService;
import com.pangu.util.StringUtil;
import com.squareup.picasso.Picasso;
import com.vancouver.knows.business.BusinessModule;
import com.vancouver.knows.business.bean.BusinessRateInfo;
import com.vancouver.knows.business.bean.CityDiscountDetailInfo;
import com.vancouver.knows.business.bean.CityNewsDetailInfo;
import com.vancouver.knows.business.bean.CommentInfo;
import com.vancouver.knows.business.bean.DiscountInfo;
import com.vancouver.knows.business.bean.EditUserInfo;
import com.vancouver.knows.business.bean.EventDetailInfo;
import com.vancouver.knows.business.bean.NameValuePair;
import com.vancouver.knows.business.bean.PostPrivacySettingInfo;
import com.vancouver.knows.business.bean.SplashAdInfo;
import com.vancouver.knows.business.bean.UploadedUserPostDetailInfo;
import com.vancouver.knows.business.bean.UserInfo;
import com.vancouver.knows.business.bean.UserPostDetailInfo;
import com.vancouver.knows.business.bean.UserRegisterInfo;
import com.vancouver.knows.business.bean.VersionInfo;

/**
 * 本地服务封装
 * <p/>
 * Created by cxlin
 */
public class BLocalService implements IService {

    public static final String TAG = BLocalService.class.getSimpleName();

    protected BHttpService bHttpService;
    private BusinessModule bModule;

    public BLocalService(BHttpService chainService, BusinessModule bModule) {
        this.bHttpService = chainService;
        this.bModule = bModule;

    }

    /**
     * 查询城事列表
     *
     * @return
     * @throws ActionException
     */
    public PageableResult fetchCityNews(List<NameValuePair> datas) throws ActionException {
        return bHttpService.fetchCityNews(datas);
    }

    /**
     * 用户登陆业务接口，email与phone选其一登陆，外部调用时注意区分
     *
     * @param email
     * @param phone
     * @param password
     * @param gcmToken
     * @return
     * @throws ActionException
     */
    public UserInfo userLogin(String email, String phone, String password, String gcmToken) throws ActionException {
        return bHttpService.userLogin(email, phone, password, gcmToken);
    }

    /**
     * 查询用户
     *
     * @param userID 用户id
     * @return
     * @throws ActionException
     */
    public UserInfo queryUserInfo(String userID) throws ActionException {
        return bHttpService.queryUserInfo(userID);
    }

    /**
     * 点赞
     *
     * @throws ActionException
     */
    public void userUpvote(List<NameValuePair> datas) throws ActionException {
        bHttpService.userUpvote(datas);
    }

    /**
     * 删除用户点赞
     *
     * @return
     */
    public void userDeleteUpvote(List<NameValuePair> datas) throws ActionException {
        bHttpService.userDeleteUpvote(datas);
    }

    /**
     * 查询活动列表
     *
     * @return
     */
    public PageableResult fetchEvents(List<NameValuePair> datas) throws ActionException {
        return bHttpService.fetchEvents(datas);
    }

    /**
     * 修改密码
     *
     * @param phone 手机号
     * @param email 邮箱
     * @return
     * @throws ActionException
     */
    public void forgotPassword(String phone, String email) throws ActionException {
        bHttpService.forgotPassword(phone, email);
    }

    /**
     * 修改密码
     *
     * @param phone        手机号
     * @param email        邮箱
     * @param verification 6位数验证码
     * @param userPassword 用户输入的新密码
     * @return
     * @throws ActionException
     */
    public void modifyPassword(String phone, String email, String verification, String userPassword)
            throws ActionException {
        bHttpService.modifyPassword(phone, email, verification, userPassword);
    }

    /**
     * 查询活动详情
     *
     * @return
     */
    public EventDetailInfo fetchEventDetail(List<NameValuePair> datas) throws ActionException {
        return bHttpService.fetchEventDetail(datas);
    }

    /**
     * 用户关注
     *
     * @return
     */
    public void userFollow(List<NameValuePair> datas) throws ActionException {
        bHttpService.userFollow(datas);
    }

    /**
     * 删除用户关注
     *
     * @return
     */
    public void userDeleteFollow(List<NameValuePair> datas) throws ActionException {
        bHttpService.userDeleteFollow(datas);
    }

    /**
     * 邮箱验证码
     *
     * @param email 邮箱
     * @throws ActionException
     */
    public void emailSendSecurityCode(String email) throws ActionException {
        bHttpService.emailSendSecurityCode(email);
    }

    /**
     * 邮箱注册
     *
     * @param email            邮箱
     * @param verificationCode 验证码
     * @param userNickName     昵称
     * @param password         密码
     * @return
     * @throws ActionException
     */
    public UserRegisterInfo emailUserRegister(String email, String verificationCode, String userNickName,
                                              String password) throws ActionException {
        return bHttpService.emailUserRegister(email, verificationCode, userNickName, password);
    }

    /**
     * 获取手机验证码
     *
     * @param email 手机号
     * @throws ActionException
     */
    public void phoneSendSecurityCode(String email) throws ActionException {
        bHttpService.phoneSendSecurityCode(email);
    }

    /**
     * 手机注册
     *
     * @param email            手机号码
     * @param verificationCode 验证吗
     * @param userNickName     用户昵称
     * @param password         密码
     * @return
     * @throws ActionException
     */
    public UserRegisterInfo phoneUserRegister(String email, String verificationCode, String userNickName,
                                              String password) throws ActionException {
        return bHttpService.phoneUserRegister(email, verificationCode, userNickName, password);
    }

    /**
     * 查询城事详情
     *
     * @return
     */
    public CityNewsDetailInfo fetchCityNewsDetail(List<NameValuePair> datas) throws ActionException {
        return bHttpService.fetchCityNewsDetail(datas);
    }

    /**
     * 用户评论
     *
     * @return
     */
    public CommentInfo userInsertComment(List<NameValuePair> datas)
            throws ActionException {
        return bHttpService.userInsertComment(datas);
    }

    /**
     * 搜索
     *
     * @param keyWord  关键字
     * @param fromType 搜索入口
     * @param from     请求页
     * @param size     请求页中个数
     * @return
     * @throws ActionException
     */
    public HashMap<String, Object> userSearch(String keyWord, String fromType, String from, String size, String complete)
            throws ActionException {
        HashMap<String, Object> map = bHttpService.userSearch(keyWord, fromType, from, size, complete);
        if (map != null) {
            map.put("keywork", keyWord);

        }
        return map;
    }

    /**
     * 查询评论列表
     *
     * @return
     */
    public PageableResult fetchComments(List<NameValuePair> datas) throws ActionException {
        return bHttpService.fetchComments(datas);
    }

    /**
     * 搜索总条数
     *
     * @return
     * @throws ActionException
     */
    public PageableResult userSearchTotal(List<NameValuePair> datas) throws ActionException {
        return bHttpService.userSearchTotal(datas);

    }

    public void saveShareImg(String imgUrl, String dir) {
        if (StringUtil.isEmptyString(imgUrl)) {
            return;
        }
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }

        String path = dir + imgUrl.hashCode() + ".jpg";
        file = new File(path);
        try {
            Bitmap bitmap = Picasso.with(bModule.getAMApplication()).load(imgUrl).get();
            if (bitmap != null) {
                try {
                    FileOutputStream out = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                    out.flush();
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 举报
     *
     * @return
     */
    public void commentReport(List<NameValuePair> datas) throws ActionException {
        bHttpService.commentReport(datas);
    }

    /**
     * 首页
     *
     * @return
     * @throws ActionException
     */
    public HashMap<String, Object> homePage(int from, int size, String version) throws ActionException {
        if (from > 0) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("from", from);
            map.put("size", size);
            return map;

        } else {
            HashMap<String, Object> map = bHttpService.homePage(version);
            map.put("from", from);
            map.put("size", size);
            return map;
        }
    }

    /**
     * 公用接口（我的文章，我的评论，@我的评论，我的关注）
     *
     * @return
     * @throws ActionException
     */
    public PageableResult myArticleFollowAndComments(List<NameValuePair> datas) throws ActionException {
        return bHttpService.myArticleFollowAndComments(datas);

    }

    public PageableResult liveFeed(List<NameValuePair> datas) throws ActionException {
        return bHttpService.liveFeed(datas);

    }

    /**
     * 发表文章
     *
     * @param userId          用户id
     * @param title           标题
     * @param content         内容
     * @param attachmentImage 上传的图片
     * @param category        类型
     * @throws ActionException
     */
    public void userPostArticle(String userId, String title, String content, List<String> attachmentImage,
                                String category) throws ActionException {
        String thumbnail = "";
        List<String> imgUrls = new ArrayList<String>();
        if (attachmentImage != null && attachmentImage.size() > 0) {
            // 获取token信息
            HashMap<String, String> cdnToken = bHttpService.getCdnToken();
            if (StringUtil.isEmptyString(cdnToken.get("tokenId"))) {
                throw new ActionException();
            }

            String token = cdnToken.get("tokenId");
            String fileUrl = cdnToken.get("cloudFiles") + "/p16";
            // 获取p16下的cdn地址
            String cdnFilesUrl = cdnToken.get("cloudFilesCDN") + "/p16";

            String cdnUrl = bHttpService.getCdnUrl(cdnFilesUrl, token);

            String time = System.currentTimeMillis() + "";
            List<String> uploadImgs = new ArrayList<String>();
            uploadImgs.add(attachmentImage.get(0));
            uploadImgs.addAll(attachmentImage);
            List<String> urls = new ArrayList<String>();
            for (int i = 0; i < uploadImgs.size(); i++) {
                String path = "/user_content/" + userId + "-" + time + "-" + i + ".jpg";
                urls.add(fileUrl + path);

                if (i == 0) {
                    thumbnail = cdnUrl + path;
                } else {
                    imgUrls.add(cdnUrl + path);
                }

            }

            // 上传图片
            bHttpService.uploadImages(token, uploadImgs, urls);
        }

        bHttpService.userPostArticle(userId, title, content, thumbnail, imgUrls, category);
    }

    public UploadedUserPostDetailInfo uploadUserPost(String userId, String postId, String content, List<String> attachmentImage, String status,
                                                     String category, String subcategory, String price, String city, String phone, String email) throws ActionException {

        String thumbnail = "";
        List<String> imgUrls = new ArrayList<String>();
        if (attachmentImage != null && attachmentImage.size() > 0) {
            // 获取token信息
            HashMap<String, String> cdnToken = bHttpService.getCdnToken();
            if (StringUtil.isEmptyString(cdnToken.get("tokenId"))) {
                throw new ActionException();
            }

            String token = cdnToken.get("tokenId");
            String fileUrl = cdnToken.get("cloudFiles") + "/p16";
            // 获取p16下的cdn地址
            String cdnFilesUrl = cdnToken.get("cloudFilesCDN") + "/p16";

            String cdnUrl = bHttpService.getCdnUrl(cdnFilesUrl, token);

            String time = System.currentTimeMillis() + "";
            List<String> uploadImgs = new ArrayList<String>();
            uploadImgs.add(attachmentImage.get(0));
            uploadImgs.addAll(attachmentImage);
            List<String> urls = new ArrayList<String>();
            for (int i = 0; i < uploadImgs.size(); i++) {
                String path = "/user_content/" + userId + "-" + time + "-" + i + ".jpg";
                urls.add(fileUrl + path);

                if (i == 0) {
                    thumbnail = cdnUrl + path;
                } else {
                    imgUrls.add(cdnUrl + path);
                }

            }

            // 上传图片
            bHttpService.uploadImages(token, uploadImgs, urls);
        }

        return bHttpService.uploadUserPost(userId, postId, content, thumbnail, imgUrls, status, category, subcategory, price, city, phone, email);
    }

    public PageableResult fetchUserPosts(List<NameValuePair> datas)
            throws ActionException {
        return bHttpService.fetchUserPosts(datas);
    }

    public PageableResult getUserPosts(List<NameValuePair> data)
            throws ActionException {
        return bHttpService.getUserPosts(data);
    }

    public HashMap<String, Object> fetchUserPostCategories(List<NameValuePair> datas)
            throws ActionException {
        return bHttpService.fetchUserPostCategories(datas);
    }

    /**
     * 查询城惠列表
     *
     * @return
     */
    public PageableResult fetchCityDiscounts(List<NameValuePair> datas)
            throws ActionException {
        return bHttpService.fetchCityDiscounts(datas);
    }

    /**
     * 根据类型查询城惠列表
     *
     * @return
     */
    public PageableResult fetchCtyDiscountCategory(List<NameValuePair> datas) throws ActionException {
        return bHttpService.fetchCtyDiscountCategory(datas);
    }

    /**
     * 获取用户反馈，关于我们，用户使用协议
     *
     * @return
     * @throws ActionException
     */
    public List<Object> myUserNotice(List<NameValuePair> datas) throws ActionException {
        return bHttpService.myUserNotice(datas);
    }

    /**
     * 删除用户评论
     *
     * @return
     */
    public void userDeleteComment(List<NameValuePair> datas) throws ActionException {
        bHttpService.userDeleteComment(datas);

    }

    /**
     * 查询城惠详情
     *
     * @return
     */
    public CityDiscountDetailInfo fetchDiscountDetail(List<NameValuePair> datas) throws ActionException {
        return bHttpService.fetchDiscountDetail(datas);
    }

    public UserPostDetailInfo fetchUserPostDetail(List<NameValuePair> data) throws ActionException {
        return bHttpService.fetchUserPostDetail(data);
    }

    /**
     * 用户图片更新
     *
     * @param userId   用户id
     * @param imageUrl 需更新的图片url
     * @return
     * @throws ActionException
     */
    public UserInfo userUploadImage(String userId, String imageUrl) throws ActionException {
        HashMap<String, String> cdnToken = bHttpService.getCdnToken();
        if (StringUtil.isEmptyString(cdnToken.get("tokenId"))) {
            throw new ActionException();
        }
        String token = cdnToken.get("tokenId");
        String fileUrl = cdnToken.get("cloudFiles") + "/p16";
        // 获取p16下的cdn地址
        String cdnFilesUrl = cdnToken.get("cloudFilesCDN") + "/p16";
        String cdnUrl = bHttpService.getCdnUrl(cdnFilesUrl, token);
        String time = System.currentTimeMillis() + "";
        String url = null;
        String imagUrls = null;
        String path = "/avatar/" + time + "-" + userId + ".jpg";
        url = fileUrl + path;
        imagUrls = cdnUrl + path;
        // 上传图片
        bHttpService.uploadImage(token, imageUrl, url, false);

        return bHttpService.userUploadImage(userId, imagUrls);

    }

    /**
     * 用户评论星级
     *
     * @return
     */
    public BusinessRateInfo userRateBusiness(List<NameValuePair> datas) throws ActionException {
        return bHttpService.userRateBusiness(datas);
    }

    /**
     * 添加用户GCM的token
     *
     * @param userId         用户id
     * @param registrationId gcm注册id
     * @param status         状态
     * @param auid           auid
     * @return
     */
    public void addUserToken(String userId, String registrationId, String status, String auid) throws ActionException {
        bHttpService.addUserToken(userId, registrationId, status, auid);
    }

    /**
     * 添加用户FCM的token
     * @param userId
     * @param fcmToken
     * @throws ActionException
     */
    public void addUserToken(String userId, String fcmToken) throws ActionException {
        bHttpService.addUserToken(userId, fcmToken);
    }

    /**
     * 删除文章
     *
     * @return
     */
    public void userDeleteArticle(List<NameValuePair> datas) throws ActionException {
        bHttpService.userDeleteArticle(datas);
    }

    /**
     * 上传推送设置
     *
     * @param userId           用户id
     * @param postReminder     文章评论推送
     * @param commentReminder  at我的评论推送
     * @param businessReminder 关注商家推送
     * @throws ActionException
     */
    public void setMessageRemind(String userId, boolean postReminder, boolean commentReminder, boolean businessReminder)
            throws ActionException {
        bHttpService.setMessageRemind(userId, postReminder, commentReminder, businessReminder);
    }

    /**
     * 获取用户推送设置
     *
     * @param userId 用户id
     * @return
     * @throws ActionException
     */
    public Map userGetNotificationSetting(String userId) throws ActionException {
        return bHttpService.userGetNotificationSetting(userId);
    }

    /**
     * 获取auid
     *
     * @param androidId
     * @param imei
     * @return
     * @throws ActionException
     */
    public String userGetAuid(String androidId, String imei) throws ActionException {
        AdvertisingIdClient.Info adInfo = null;
        String adid = null;
        try {
            adInfo = AdvertisingIdClient.getAdvertisingIdInfo(bModule.getAMApplication());
            adid = adInfo.getId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        adid = adid == null ? "" : adid;

        return bHttpService.userGetAuid(androidId, imei, adid);
    }

    /**
     * 获取userIdHash
     *
     * @param userId
     * @param auid
     * @return
     * @throws ActionException
     */
    public String userHash(String userId, String auid) throws ActionException {
        return bHttpService.userHash(userId, auid);
    }

    /**
     * 版本更新
     *
     * @return
     * @throws ActionException
     */
    public VersionInfo updateVersion() throws ActionException {
        return bHttpService.updateVersion();
    }

    /**
     * 开屏广告
     * @return
     * @throws ActionException
     */
    public SplashAdInfo sendSplashAd() throws ActionException {
        return bHttpService.sendSplashAd();
    }

    /**
     * 地图查询城惠信息
     *
     * @return
     * @throws ActionException
     */
    public  List<DiscountInfo> homeMap(List<NameValuePair> datas) throws ActionException {
        return bHttpService.homeMap(datas);
    }

    public EditUserInfo editUserProfile(List<NameValuePair> datas) throws ActionException {
        return bHttpService.editUserProfile(datas);
    }

    public void resetPassword(List<NameValuePair> data) throws ActionException {
        bHttpService.resetPassword(data);
    }

    public PostPrivacySettingInfo setListingsPrivacy(List<NameValuePair> data) throws ActionException {
        return bHttpService.setListingsPrivacy(data);
    }

    public void renewUserPost(List<NameValuePair> data) throws ActionException {
        bHttpService.renewUserPost(data);
    }

    public PageableResult fetchMyUserPostComments(List<NameValuePair> data) throws ActionException {
        return bHttpService.fetchMyUserPostComments(data);
    }

    public PageableResult fetchUserBusinessImages(List<NameValuePair> data) throws ActionException {
        return bHttpService.fetchUserBusinessImages(data);
    }

    public void deleteUserBusinessImages(List<NameValuePair> data) throws ActionException {
        bHttpService.deleteUserBusinessImages(data);
    }

    public void uploadBusinessPhotos(String userId, String postId, List<String> attachmentImage,
                                String caption) throws ActionException {
        List<String> imgUrls = new ArrayList<String>();
        if (attachmentImage != null && attachmentImage.size() > 0) {
            // 获取token信息
            HashMap<String, String> cdnToken = bHttpService.getCdnToken();
            if (StringUtil.isEmptyString(cdnToken.get("tokenId"))) {
                throw new ActionException();
            }

            String token = cdnToken.get("tokenId");
            String fileUrl = cdnToken.get("cloudFiles") + "/p16";
            // 获取p16下的cdn地址
            String cdnFilesUrl = cdnToken.get("cloudFilesCDN") + "/p16";

            String cdnUrl = bHttpService.getCdnUrl(cdnFilesUrl, token);

            String time = System.currentTimeMillis() + "";
            List<String> uploadImgs = new ArrayList<String>();
            uploadImgs.addAll(attachmentImage);
            List<String> urls = new ArrayList<String>();
            for (int i = 0; i < uploadImgs.size(); i++) {
                String path;
                if (BHttpService.DOMAIN.equals("api.vanknow.com/2.0.1/")) {
                    path = "/user_content/business_images/test/" + userId + "-" + postId + "-" + time + "-" + i + ".jpg";
                } else {
                    path = "/user_content/business_images/" + userId + "-" + postId + "-" + time + "-" + i + ".jpg";
                }
                urls.add(fileUrl + path);
                imgUrls.add(cdnUrl + path);
            }

            // 上传图片
            bHttpService.uploadImages(token, uploadImgs, urls);
        }

        bHttpService.uploadBusinessPhotos(userId, postId, imgUrls, caption);
    }

}
